//
//  TSRootViewController.swift
//  TopStock
//
//  Created by dyd on 2017/8/12.
//  Copyright © 2017年 dyd. All rights reserved.
//

import UIKit
import CoreTelephony

extension UIBarButtonItem{
    struct RuntimeKey {
        static let fucStr = UnsafeRawPointer.init(bitPattern: "FucStr".hashValue)
        static let imgStr = UnsafeRawPointer.init(bitPattern: "ImgStr".hashValue)
    }
    var funcString: String? {
        set {
            objc_setAssociatedObject(self, UIBarButtonItem.RuntimeKey.fucStr, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        get {
            return  objc_getAssociatedObject(self, UIBarButtonItem.RuntimeKey.fucStr) as? String
        }
    }
    var imgUrlString:String?
    {
        set {
            objc_setAssociatedObject(self, UIBarButtonItem.RuntimeKey.imgStr, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        get {
            return  objc_getAssociatedObject(self, UIBarButtonItem.RuntimeKey.imgStr) as? String
        }
    }
}

import JavaScriptCore
class TSRootViewController: UIViewController,UIWebViewDelegate,UISearchBarDelegate,JavaScriptModelDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TSDatePickerViewControllerDelegate,ClipImageDelegate,NSURLConnectionDataDelegate{
    @IBOutlet weak var backBarButtonItem: UIBarButtonItem!
//    @IBOutlet weak var webView: UIWebView!
    
    var portStr = "https://www.topstock.xyz"
//    var portStr = "https://www.topstock.xyz/bridge.html"
//    var portStr = "https://www.topstock.xyz/#/self/authSelect"
    var jsContext = JSContext()
    var requestDic = NSDictionary()
    var rightActionFn:String? = nil
    var newModelContext:JSContext? = nil
    var newJSFunc:String? = nil
    var searchFunc:String? = nil
    var searchContext:JSContext? = nil
    let searchbar = UISearchBar(frame: CGRect(x:0, y: 0, width: 100, height: 20))
    lazy var webView = UIWebView()
    var isFromAuthentic:Bool = false
//    var activityIndicator:UIActivityIndicatorView!
    var contextForuUpload:JSContext? = nil
    var funcForuUpload:String? = nil
    let toast = ToastView()
    var aspectType = 1
    
    let tsRequest = TSRequestData()
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(webViewRefresh), name: NSNotification.Name(rawValue: "webViewRefresh"), object: nil)
        UIApplication.shared.statusBarStyle = .`default`
        setNavBarAppearance()
        if isFromAuthentic{
            portStr = "https://www.topstock.xyz/#/self/authSelect"
        }
        addWebView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.view.layoutIfNeeded()
        // webView.scrollView.contentInset = UIEdgeInsets.zero
        
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        webView.scrollView.contentInset = UIEdgeInsets.zero
    }
    
//    func addActivityIndicator()
//    {
//        activityIndicator = UIActivityIndicatorView(activityIndicatorStyle:
//            UIActivityIndicatorViewStyle.gray)
//        activityIndicator.center = self.view.center
//        self.view.addSubview(activityIndicator);
//    }
    
    //进度条开始转动
    func showLoading(){
        toast.showLoadingDlg()
    }
    
    //进度条停止转动
    func stopLoading(){
        toast.stopLoading()
    }
    
    func webViewRefresh(notification:NSNotification){
        portStr = "https://www.topstock.xyz"
        if notification.userInfo != nil{
            let isAuthentic = notification.userInfo?["isAuthentic"] as! Bool
            if isAuthentic{
                portStr = "https://www.topstock.xyz/#/self/authSelect"
                isFromAuthentic = true
            }else{
                portStr = "https://www.topstock.xyz"
                isFromAuthentic = false
            }
        }
        addWebView()
    }
    
    func addSearchBar(){
        searchbar.backgroundColor = UIColor.clear
        searchbar.barStyle = UIBarStyle.default
        searchbar.barTintColor = UIColor.clear
        searchbar.tintColor = UIColor.white
        searchbar.searchBarStyle = UISearchBarStyle.minimal
        for subView in searchbar.subviews  {
            for subsubView in subView.subviews  {
                if let textField = subsubView as? UITextField {
                    textField.backgroundColor = UIColor.blue
                    textField.layer.borderColor = UIColor.green.cgColor
                    textField.layer.cornerRadius = 10
                    textField.textColor = UIColor.white
                }
            }
        }
        searchbar.delegate = self
        // 键盘类型设置
        searchbar.keyboardType = UIKeyboardType.twitter
        searchbar.returnKeyType = UIReturnKeyType.search
        self.navigationItem.titleView = nil
    }

    //MARK: -设置NavigationBar上的 LeftBarbuttonItem， 中间NavigationItem.titleView，右边RightBarbuttonItem
    
    //设置左边按钮
    func setLeftBarButtonItem(titleType:TitleType,
                              title:String?,
                              funStr:String?,
                              imgUrl:String?)
    {
        self.navigationItem.leftBarButtonItem = nil
        var leftBarBtnItem:UIBarButtonItem? = nil
        switch titleType {
        case .BACK:
            leftBarBtnItem = UIBarButtonItem(title: " ", style: .plain, target: self, action: #selector(goBackForWebView))
            leftBarBtnItem?.image = UIImage(named: "backPress")
        case .IMG:
            leftBarBtnItem = UIBarButtonItem(title: " ", style: .plain, target: self, action:#selector(leftBarButtonItemAction(sender:)))
            if (imgUrl != nil){
                downImage(urlString: imgUrl!, barBtnItem: leftBarBtnItem!)
            }
        default:
            break
        }
        leftBarBtnItem?.funcString = funStr
        self.navigationItem.leftBarButtonItem = leftBarBtnItem
        self.navigationItem.leftBarButtonItem?.tintColor = BarButtonItemTintColor
    }
    
    //设置NavigationItem上的TitleView
    func setNavigationItemTitleView(titleType:TitleType,
                                    title:String?,
                                    funStr:String?,
                                    imgUrl:String?)
    {
        self.navigationItem.titleView = nil
        switch titleType {
        case .TITLE:
            self.title = title
        case .SEARCH:
            searchbar.placeholder = title
            searchFunc = funStr
            searchbar.returnKeyType = UIReturnKeyType.search
            self.navigationItem.titleView = searchbar
        default:
            break
        }
    }
    
    //设置右边按钮
    func setRightBarButtonItem(titleType:TitleType,
                               title:String?,
                               funStr:String?,
                               imgUrl:String?)
    {
        self.navigationItem.rightBarButtonItem = nil
        var rightBarBtnItem:UIBarButtonItem? = nil
        switch titleType {
        case .BUTTON:
            rightBarBtnItem = UIBarButtonItem(title: title, style: .plain, target: self, action:#selector(rightBarbuttonItemAction(sender:)))
        case .IMG:
            rightBarBtnItem = UIBarButtonItem(title: " ", style: .plain, target: self, action:#selector(rightBarbuttonItemAction(sender:)))
            if (imgUrl != nil){
                downImage(urlString: imgUrl!, barBtnItem: rightBarBtnItem!)
            }
        case .MIDDLESEARCH:
            rightBarBtnItem = UIBarButtonItem(title: title, style: .plain, target: self, action:#selector(searchResultClicked(sender:)))
            searchbar.returnKeyType = UIReturnKeyType.`default`
            
        default:
            break
        }
        rightBarBtnItem?.funcString = funStr
        self.navigationItem.rightBarButtonItem = rightBarBtnItem
        self.navigationItem.rightBarButtonItem?.tintColor = BarButtonItemTintColor
        
    }
    
    func leftBarButtonItemAction(sender:UIBarButtonItem)
    {
        let parmar = ""
        let jsFunction = NSString.init(format: "%@('%@')",sender.funcString!,parmar) as String
        let _ = newModelContext?.evaluateScript(jsFunction)
    }
    
    func searchResultClicked(sender:UIBarButtonItem)
    {
        let parmar = searchbar.text
        let jsonDic = ["key":parmar]
        let jsonStr = getJSONStringFromDictionary(dictionary: jsonDic as NSDictionary)
//        let jsFunction = NSString.init(format: "%@('%@')",sender.funcString!,jsonStr) as String
        let jsFunction = NSString.init(format: "%@('%@')",searchFunc!,jsonStr) as String
        let _ = searchContext?.evaluateScript(jsFunction)
    }
    
    func rightBarbuttonItemAction(sender:UIBarButtonItem)
    {
        let parm = ""
//        let jsonDic = ["key":parm]
//        let jsonStr = getJSONStringFromDictionary(dictionary: jsonDic as NSDictionary)
        let jsFunction = NSString.init(format: "%@('%@')",sender.funcString!,parm) as String
        let _ = newModelContext?.evaluateScript(jsFunction)
    }
    
    //.设置导航栏标题颜色
    func setNavBarAppearance(){
        let navBar=UINavigationBar.appearance()
        navBar.titleTextAttributes = NavBarTitleTextAttributes
        navBar.tintColor = UIColor.black
        navBar.barTintColor = BarTintColor
        UIApplication.shared.statusBarStyle = .lightContent
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func addWebView(){
        webView.removeFromSuperview()
        webView = UIWebView()
        let statusBarHeight = UIApplication.shared.statusBarFrame.height
        let navigationBarHeight:CGFloat = 44
        let trainY = statusBarHeight + navigationBarHeight
        self.view.addSubview(webView)
        webView.translatesAutoresizingMaskIntoConstraints = false
        webView.snp.makeConstraints { (make) in
            make.top.equalTo(trainY)
            make.bottom.equalTo(view)
            make.left.equalTo(view)
            make.right.equalTo(view)
        }
        webView.scrollView.bounces = false
        webView.scrollView.isScrollEnabled = false
        webView.scalesPageToFit = true
        webView.sizeToFit()
        webView.delegate = self
        let url = URL.init(string: portStr)
        let request = URLRequest(url: url!)
        self.webView.loadRequest(request)
        setJSContext(url: url! as NSURL)
        addSearchBar()
//        addActivityIndicator()
    }
    
    func setJSContext(url:NSURL){
        jsContext = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as? JSContext
        let model = SwiftJavaScriptModel()
        model.delegate = self
        model.jsModelContext = jsContext
        self.jsContext?.setObject(model, forKeyedSubscript: "nativeBridge" as NSCopying & NSObjectProtocol)
    }
    
    func goBackForWebView(){
        if isFromAuthentic{
            self.dismiss(animated: true, completion: nil)
        }else{
            setDeviceOrientation(isPortrait: true)
            webView.goBack()
        }
    }
    
    // MARK: - WebView delegate
    
    func webViewDidStartLoad(_ webView: UIWebView){
        DispatchQueue.main.async(execute: {
            self.showLoading()
        })
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        webView.stringByEvaluatingJavaScript(from: "document.documentElement.style.webkitUserSelect='none'")
        webView.stringByEvaluatingJavaScript(from: "document.documentElement.style.webkitTouchCallout='none'")
        DispatchQueue.main.async(execute: {
            self.stopLoading()
        })

    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        print("webview")
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        if (request.debugDescription == "https://www.topstock.xyz/undefined"){
            return false
        }
//        let states = Reachability.getNetWorkStates() as String
//        var interval:TimeInterval = 0.5
//        switch states {
//        case "2G":
//            interval = 4
//        case "3G":
//            interval = 3
//        case "4G":
//            print("4G")
//            interval = 0.5
//        case "WIFI":
//            interval = 0.5
//        case "无网络":
//            interval = 60
//        default:
//            interval = 60
//        }
//        if((request.debugDescription == "https://www.topstock.xyz/#/") ||
//            (request.debugDescription == "https://www.topstock.xyz/#/products") ||
//            (request.debugDescription == "https://www.topstock.xyz/#/information") ||
//            (request.debugDescription == "https://www.topstock.xyz/#/self"))
//        {
//            DispatchQueue.main.async(execute: {
//                self.showLoading()
//            })
//            let mySession = URLSession(configuration: URLSessionConfiguration.default)
//            let dataTask = mySession.dataTask(with: request, completionHandler: { (data, response, error) in
//                DispatchQueue.main.async(execute: {
//                    self.perform(#selector(self.stopLoading), with: nil, afterDelay: interval)
//                })
//            })
//            dataTask.resume()
//        }
        return true
    }
    
    // MARK: - UISearchBar delegate
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        let parmar = searchBar.text
        let jsonDic = ["key":parmar]
        let jsonStr = getJSONStringFromDictionary(dictionary: jsonDic as NSDictionary)
        let jsFunction = NSString.init(format: "%@('%@')",searchFunc!,jsonStr) as String
        let _ = searchContext?.evaluateScript(jsFunction)
    }
    
    // MARK: - JavaScriptModelDelegate
    func JavaScriptCallBackFunc(jsonDic:NSDictionary?,modelContext:JSContext,eventType:JSEventType){
        switch eventType {
        case .OpenUrl://新开网页
            openUrl(jsonDic: jsonDic, modelContext: modelContext)
        case .Camerra://唤起摄像头
            getCamerra(jsonDic: jsonDic, modelContext: modelContext)
        case .NetStatus://查看当前网络状态
            getNetStatus()
        case .UserInfo://获取当前用户信息
            getUser(jsonDic: jsonDic, modelContext: modelContext)
        case .UserLogin://唤起用户登陆
            getUserLogin(isFromSetting: false)
        case .GetUserLogout://用户退出登陆
            getUserLogout()
        case .GetUserEditPassword:
            getUserEditPassword()//唤起修改密码
        case .Sheet://唤起下拉选择框
            setSheet(jsonDic: jsonDic, modelContext: modelContext)
        case .SheetTime://唤起时间下拉选择框
            setSheetTime()
        case .SheetDate://唤起日期下拉选择框
            setSheetDate()
        case .Alert://消息提示框
            setAlert(jsonDic: jsonDic, modelContext: modelContext)
        case .QRcode://二维码扫描
            getQRcode()
        case .TOTAST_LOADING,.TOTAST_SUCCESS,.TOTAST_ERROR,.TOTAST_CANCEL://载入/完成/错误/取消
            setTotast(jsonDic: jsonDic,eventType: eventType)
        case .Share://分享
            setShare(jsonDic: jsonDic, modelContext: modelContext)
        case .OpenCalenda://打开日历
            openCalendar(jsonDic: jsonDic, modelContext: modelContext)
        case .HelpInterface://帮助文字
            setHelpInterface()
        case .SetTitle://设置标题
            setTitle(jsonDic: jsonDic, modelContext: modelContext)
        case .GetCache://获取缓存大小
            getCache(jsonDic: jsonDic, modelContext: modelContext)
        case .ClearCache://清除缓存
            clearCache(jsonDic: jsonDic, modelContext: modelContext)
        case .OpenTel://打电话
            openTel(jsonDic: jsonDic, modelContext: modelContext)
        case .GetPushId://获取推送id
            getPushId()
        case .GetClipBoard://获取剪切板内容
            getClipBoard(jsonDic:jsonDic,modelContext:modelContext)
        case .SetClipBoard://设置剪切板内容
            setClipBoard(jsonDic:jsonDic,modelContext:modelContext)
        case .OpenVideo://打开视频
            openVideo(jsonDic: jsonDic)
        case .SetOrientation://设置屏幕翻转
            setOrientation(jsonDic: jsonDic, modelContext: modelContext)
        default:
            break
        }
    }

    //MARK: - 新开网页
    func openUrl(jsonDic:NSDictionary?,modelContext:JSContext)
    {
        OperationQueue.main.addOperation(){
            let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let openUrlController = storyBoard.instantiateViewController(withIdentifier: "openUrlController") as! TSOpenUrlController
            openUrlController.urlDic = jsonDic
            let nav = UINavigationController.init(rootViewController: openUrlController)
            self.present(nav, animated: true, completion: nil)
        }
    }
    //MARK: - 唤起摄像头
    func getCamerra(jsonDic:NSDictionary?,modelContext:JSContext)
    {
        funcForuUpload = jsonDic?["jsFn"] as? String
        contextForuUpload = modelContext
        aspectType = jsonDic?["type"] as! Int
        let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        //定义取消按钮及事件
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: {
            (UIAlertAction)->Void in
        })
        //定义确定按钮及事件
        let camerraAction = UIAlertAction(title: "拍照", style: .default, handler:{
            (UIAlertAction) -> Void in
            self.getImageFromSourceType(sourceType: .camera)
        })
        
        let photoAlbumAction = UIAlertAction(title: "从手机相册选择", style: .default, handler:{
            (UIAlertAction) -> Void in
            self.getImageFromSourceType(sourceType: .photoLibrary)
        })
        alertController.addAction(cancelAction)
        alertController.addAction(camerraAction)
        alertController.addAction(photoAlbumAction)
        DispatchQueue.main.async(){
            self.present(alertController, animated: true, completion: nil)
        }
    }
    
    //MARK: - 查看当前网络状态
    func getNetStatus()
    {
        
    }

    //MARK: - 获取当前用户信息
    func getUser(jsonDic:NSDictionary?,modelContext:JSContext)
    {
        let jsFuncStr = jsonDic?["jsFn"]
        let dic = tsRequest.getUserInfo()
        let dataDic = dic?["data"] as? NSDictionary
        var parmar = ""
        if dataDic != nil{
            let data = NSMutableDictionary(dictionary: dataDic!)
            data.setObject(tsRequest.getAccessToken()!, forKey: "token" as NSCopying)
            parmar = getJSONStringFromDictionary(dictionary: data)
        }
        let jsFunction = NSString.init(format: "%@('%@')",jsFuncStr as! CVarArg,parmar) as String
        let _ = modelContext.evaluateScript(jsFunction)
    }
    
    //MARK: - 唤起用户登陆
    func getUserLogin(isFromSetting:Bool)
    {
        OperationQueue.main.addOperation(){
            let storyBoard : UIStoryboard = UIStoryboard(name: "Login", bundle: nil)
            let loginViewController = storyBoard.instantiateViewController(withIdentifier: "LoginView") as! TSLoginViewController
            loginViewController.isFromSetting = isFromSetting
            let nav = UINavigationController.init(rootViewController: loginViewController)
            self.present(nav, animated: true, completion: nil)
        }
    }
    
    //MARK: - 用户退出登陆
    func getUserLogout()
    {
        if checkLoginStatus(){
            let alertController = UIAlertController(title: "温馨提示", message: "您确定要退出登陆吗？", preferredStyle: .alert)
            //定义取消按钮及事件
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: {
                (UIAlertAction)->Void in
                //TODO
            })
            //定义确定按钮及事件
            let otherAction = UIAlertAction(title: "确定", style: .default, handler:{
                (UIAlertAction) -> Void in
                let jsDic = self.tsRequest.logout()
                if jsDic != nil{
                    let success = jsDic?["success"] as! Bool
                    if success{
                        //                    self.goBackForWebView()
                        self.getUserLogin(isFromSetting: true)
                    }else{
                        let errorDic = jsDic?["error"] as? NSDictionary
                        if errorDic != nil{
                            let errorInfo = errorDic?["errorInfo"]
                            self.showAlertView(title: "", message: errorInfo as? String)
                        }
                    }
                }
            })
            
            alertController.addAction(cancelAction)
            alertController.addAction(otherAction)
            DispatchQueue.main.async(){
                self.present(alertController, animated: true, completion: nil)
            }
        }else{
            return
        }
    }
    
    //MARK: - 唤起修改密码
    func getUserEditPassword(){
        let storyBoard : UIStoryboard = UIStoryboard(name: "Login", bundle: nil)
        let foundPasswordController = storyBoard.instantiateViewController(withIdentifier: "FoundPasswordViewController") as! TSFoundPasswordViewController
        foundPasswordController.title = "修改密码"
        foundPasswordController.isFromSetting = true
        let nav = UINavigationController.init(rootViewController: foundPasswordController)
        DispatchQueue.main.async(){
            self.present(nav, animated: true, completion: nil)
        }
    }
    
    //MARK: - 唤起下拉选择框
    func setSheet(jsonDic:NSDictionary?,modelContext:JSContext)
    {
        OperationQueue.main.addOperation(){
            let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let datePickerController = storyBoard.instantiateViewController(withIdentifier: "datePickerViewController") as! TSDatePickerViewController
            datePickerController.jsFn = jsonDic?["jsFn"] as? String
            datePickerController.modelContext = modelContext
            datePickerController.view.backgroundColor = UIColor.clear
            datePickerController.providesPresentationContextTransitionStyle = true
            datePickerController.definesPresentationContext = true
            datePickerController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
            datePickerController.delegate = self
            datePickerController.modalTransitionStyle = .crossDissolve
            self.present(datePickerController, animated: true, completion: nil)
        }
    }
    //MARK: - 唤起时间下拉选择框
    func setSheetTime()
    {
        
    }
    
    //MARK: - 唤起日期下拉选择框
    func setSheetDate()
    {
        
    }
    //MARK: - 消息提示框
    func setAlert(jsonDic:NSDictionary?,modelContext:JSContext){
        if jsonDic != nil{
            let value = jsonDic?["value"] as? String
            if value != nil{
                showAlertView(title: "", message: value)
            }
        }
    }
    
    //MARK: - 二维码扫描
    func getQRcode()
    {
        
    }
    
    //MARK: - Totast 载入/完成/错误/取消
    func setTotast(jsonDic:NSDictionary?,eventType:JSEventType){
        if jsonDic != nil
        {
            let value = jsonDic?["data"] as? String
            if value != nil
            {
                showTotastAlert(value: value!)
            }
        }
        
//        switch eventType {
//        case .TOTAST_LOADING:
//            showTotastAlert(value: "载入")
//            break
//        case .TOTAST_SUCCESS:
//            showTotastAlert(value: "完成")
//            break
//        case .TOTAST_ERROR:
//            showTotastAlert(value: "错误")
//            break
//        case .TOTAST_CANCEL:
//            showTotastAlert(value: "取消")
//            break
//        default:
//            break
//        }
    }
    
    func showTotastAlert(value:String){
        DispatchQueue.main.async(){
            let attributedStr = self.appendColorStrWithString2(str: value, font: 18, color: UIColor.white)
            let alertController = UIAlertController(title:nil,message: nil, preferredStyle: .alert)
            alertController.setValue(attributedStr, forKey: "attributedMessage")
            let firstSubview = alertController.view.subviews.first
            let artContentView = firstSubview?.subviews.first
            for subview in (artContentView?.subviews)! {
                subview.backgroundColor = UIColor.black
            }
            self.present(alertController, animated: true, completion: {
                let time: TimeInterval = 2.0
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
                    alertController.dismiss(animated: true, completion: nil)
                }
            })
        }
    }
    
    private func appendColorStrWithString1(str:String,font:CGFloat,color:UIColor) -> String {
        var attributedString : NSMutableAttributedString
        let attStr = NSMutableAttributedString.init(string: str, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: font),NSForegroundColorAttributeName:color])
        attributedString = NSMutableAttributedString.init(attributedString: attStr)
        return attributedString.string
    }
    
    private func appendColorStrWithString2(str:String,font:CGFloat,color:UIColor) -> NSMutableAttributedString {
        var attributedString : NSMutableAttributedString
        let attStr = NSMutableAttributedString.init(string: str, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: font),NSForegroundColorAttributeName:color])
        attributedString = NSMutableAttributedString.init(attributedString: attStr)
        return attributedString
    }
    
    //MARK: - 关闭Totast
    func closeTotast()
    {
        
    }
    
    //MARK: - 分享
    func setShare(jsonDic:NSDictionary?,modelContext:JSContext)
    {
        let title = jsonDic?["title"] as? String
        let url = jsonDic?["url"] as? String
        share(title: title, url: url)
    }
    
    //MARK: - 打开日历
    func openCalendar(jsonDic:NSDictionary?,modelContext:JSContext)
    {
        NotificationCenter.default.addObserver(self, selector: #selector(getCalendars), name: NSNotification.Name(rawValue: "getCalendars"), object: nil)
        OperationQueue.main.addOperation(){
            let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let calendarViewController = storyBoard.instantiateViewController(withIdentifier: "CalendarViewController") as! LTSCalendarViewController
            let rootNav = UINavigationController.init(rootViewController: calendarViewController)
            self.navigationController?.present(rootNav, animated: true, completion: nil)
        }
    }

    func getCalendars(notification:NSNotification)
    {
        let date = notification.object as? Date
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let dateStr = formatter.string(from: date!)
        let jsonDic = tsRequest.getCalendars(apply_time: dateStr)
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "getCalendarInfoMation"), object: jsonDic)
    }
    
//    func setCalendarDate(notification:NSNotification){
//        var dateStr = notification.object as! String
//        dateStr = stringToTimeStamp(stringTime: dateStr)
//        let dic = ["key":dateStr]
//        let jsonStr = getJSONStringFromDictionary(dictionary: dic as NSDictionary)
//        let jsFunction = NSString.init(format: "%@('%@')",newJSFunc!,jsonStr) as String
//        let _ = self.newModelContext?.evaluateScript(jsFunction)
//        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "setCalendarDate"), object: nil)
//    }
    
//    //时间转成时间戳
//    func stringToTimeStamp(stringTime:String)->String {
//        let datefmatter = DateFormatter()
//        datefmatter.dateFormat="yyyy-MM-dd HH:mm:ss"
//        let date = datefmatter.date(from: stringTime)
//        let dateStamp:TimeInterval = date!.timeIntervalSince1970
//        let time = Int(dateStamp)
//        let millisecond = CLongLong(round(Double(time*1000)))
//        return String(millisecond)
//    }

    
    
    
    //MARK: - 帮助文字
    func setHelpInterface()
    {
        
    }
    //MARK: - 设置标题
    func setTitle(jsonDic:NSDictionary?,modelContext:JSContext)
    {
        var leftDic:NSDictionary? = nil
        var middleDic:NSDictionary? = nil
        var rightDic:NSDictionary? = nil
        leftDic = jsonDic?["left"] as? NSDictionary
        print("leftDic ==:\(String(describing: leftDic))")
        middleDic = jsonDic?["middle"] as? NSDictionary
        rightDic = jsonDic?["right"] as? NSDictionary
        DispatchQueue.main.async(){
            self.navigationItem.titleView = nil
            let middleType = middleDic?["type"] as? String
            let leftType = leftDic?["type"] as? String
            let rightType = rightDic?["type"] as? String
            //设置左边Item
            if (leftType != nil)
            {
                let funStr = leftDic?["jsFn"] as? String
                let imgUrl = leftDic?["imgSrc"] as? String
                self.newModelContext = modelContext
                if (leftType == "BACK"){
                    self.setLeftBarButtonItem(titleType: .BACK,
                                              title: nil,
                                              funStr: nil,
                                              imgUrl: nil)
                }
                else if (leftType == "IMG"){
                    self.setLeftBarButtonItem(titleType: .IMG,
                                              title: nil,
                                              funStr: funStr,
                                              imgUrl: imgUrl)
                }
            }else{
                self.navigationItem.leftBarButtonItem = nil
            }
            
            //设置中间TitleView
            if (middleType != nil){
                let funStr = middleDic?["jsFn"] as? String
                let imgUrl = middleDic?["imgSrc"] as? String
                let title = middleDic?["text"] as? String
                if (middleType == "TITLE"){
                    self.setNavigationItemTitleView(titleType: .TITLE,
                                                    title: title,
                                                    funStr: nil,
                                                    imgUrl: nil)
                }
                if (middleType == "SEARCH"){
                    self.searchContext = modelContext
                    let placeholderStr = middleDic?["text"] as? String
                    self.setNavigationItemTitleView(titleType: .SEARCH,
                                                    title: placeholderStr,
                                                    funStr: funStr,
                                                    imgUrl: imgUrl)
                }
            }else{
                self.navigationItem.titleView = nil
            }
            
            //设置右边Item
            if (rightType != nil){
                let funStr = rightDic?["jsFn"] as? String
                let imgUrl = rightDic?["imgSrc"] as? String
                let text = rightDic?["text"] as? String
                self.newModelContext = modelContext
                if (rightType == "BUTTON"){
                    let jsFn = rightDic?["jsFn"] as? String
                    if jsFn != nil
                    {
                        self.rightActionFn = jsFn
                    }
                    self.setRightBarButtonItem(titleType: .BUTTON,
                                               title: text,
                                               funStr: funStr,
                                               imgUrl: nil)
                }
                else if (rightType == "IMG"){
                    self.setRightBarButtonItem(titleType: .IMG,
                                               title: nil,
                                               funStr: funStr,
                                               imgUrl: imgUrl)
                }else if (rightType == "MIDDLESEARCH")
                {
                    self.setRightBarButtonItem(titleType: .MIDDLESEARCH,
                                               title: text,
                                               funStr: funStr,
                                               imgUrl: imgUrl)
                }
            }else{
                self.navigationItem.rightBarButtonItem = nil
            }
        }
    }
    
    //MARK: - 获取缓存大小
    func getCache(jsonDic:NSDictionary?,modelContext:JSContext)
    {
        
        if jsonDic != nil{
            let jsFn = jsonDic?["jsFn"]
            let sizef = String(getFileSizeOfCache()) + "M"
            let dic = ["key":sizef]
            let jsonStr = getJSONStringFromDictionary(dictionary: dic as NSDictionary)
            let jsFunction = NSString.init(format: "%@('%@')",jsFn! as! CVarArg,jsonStr) as String
            let _ = modelContext.evaluateScript(jsFunction)
        }
    }
    
    //MARK: - 清除缓存
    func clearCache(jsonDic:NSDictionary?,modelContext:JSContext)
    {
        if jsonDic != nil
        {
            clearFileSizeOfCache()
            let jsFn = jsonDic?["jsFn"]
            let dic = ["key":"0M"]
            let jsonStr = getJSONStringFromDictionary(dictionary: dic as NSDictionary)
            let jsFunction = NSString.init(format: "%@('%@')",jsFn! as! CVarArg,jsonStr) as String
            let _ = modelContext.evaluateScript(jsFunction)
        }
    }
    
    //MARK: - 打电话
    func openTel(jsonDic:NSDictionary?,modelContext:JSContext){
        if jsonDic != nil{
            let telNum = jsonDic?["data"] as! String
            let urlString = "tel://" + telNum
            if let url = URL(string: urlString) {
                //根据iOS系统版本，分别处理
                if #available(iOS 10, *) {
                    UIApplication.shared.open(url, options: [:],
                                              completionHandler: {
                                                (success) in
                    })
                } else {
                    UIApplication.shared.openURL(url)
                }
            }
        }
    }
    //MARK: - 获取推送id
    func getPushId()
    {
        
    }
    
    //MARK: -获取剪切板内容
    func getClipBoard(jsonDic:NSDictionary?,modelContext:JSContext)
    {
        print("getClipBoard ==>:\(String(describing: jsonDic))")
    }
    
    //MARK:-设置剪切板内容
    func setClipBoard(jsonDic:NSDictionary?,modelContext:JSContext)
    {
        if jsonDic != nil
        {
            let value = jsonDic?["value"] as? String
            UIPasteboard.general.string = value
            DispatchQueue.main.async(){
                let alertController = UIAlertController(title: "复制成功",message: nil, preferredStyle: .alert)
                self.present(alertController, animated: true, completion: {
                    alertController.dismiss(animated: true, completion: nil)
                })
            }
        }
    }
    
    //MARK: -打开视频
    func openVideo(jsonDic:NSDictionary?)
    {
        let data = jsonDic?["data"] as? String
        if data != nil
        {
            let videoDic = tsRequest.informationDetail(id: data)["data"] as? NSDictionary
            if videoDic != nil
            {
                OperationQueue.main.addOperation(){
                    NotificationCenter.default.addObserver(self, selector: #selector(self.addVideoViewingTime), name: NSNotification.Name(rawValue: "addVideoViewingTime"), object: nil)
                    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                    let openVideoController = storyBoard.instantiateViewController(withIdentifier: "openVideoController") as! TSOpenVideoController
                    openVideoController.moveInfoMationDic = videoDic
                    openVideoController.view.backgroundColor = UIColor.white
                    let item = UIBarButtonItem(title: " ", style: .plain, target: self, action: nil)
                    self.navigationItem.backBarButtonItem = item
                    self.navigationController?.pushViewController(openVideoController, animated: true)
                }
            }else{
                showAlertView(title: "无效的视频", message: nil)
            }
        }else{
            showAlertView(title: "无效的视频", message: nil)
        }
    }
    
    //增加视频观看时间
    func addVideoViewingTime(notification:NSNotification)
    {
        let currentPlayTime = notification.object as! Double
        print("currentPlayTime ==>:\(currentPlayTime)");
        _ = tsRequest.addVideoViewingTime(videoTime: currentPlayTime)
    }
    
    
    //MARK: -设置横竖屏幕
    func setOrientation(jsonDic:NSDictionary?,modelContext:JSContext)
    {
        setDeviceOrientation(isPortrait: false)
        let parmar = ""
        let jsFuncStr = jsonDic?["jsFn"]
        let jsFunction = NSString.init(format: "%@('%@')",jsFuncStr as! CVarArg,parmar) as String
        let _ = modelContext.evaluateScript(jsFunction)
    }
    
    func showAlertView(title:String?,message:String?){
        let alert = UIAlertController.init(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction.init(title: "确定", style: .`default`, handler: {
            (UIAlertAction) -> Void in
            //TODO
        }))
        DispatchQueue.main.async(){
            self.present(alert, animated: true, completion: nil)
        }
    }
    
    
    //
    func getImageFromSourceType(sourceType:UIImagePickerControllerSourceType)
    {
        let imagePicker = UIImagePickerController()
        let isAvailable = UIImagePickerController.isSourceTypeAvailable(sourceType)
        imagePicker.sourceType = sourceType
        imagePicker.delegate = self
//        imagePicker.allowsEditing = true
        imagePicker.navigationBar.tintColor = BarButtonItemTintColor
        if isAvailable{
            DispatchQueue.main.async(){
                self.present(imagePicker,
                             animated: true, completion:nil)
            }
        }
    }
    
    //MARK:- UIImagePickerControllerDelegate
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        self.dismiss(animated: true, completion: nil)
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        let clipImageVC = ClipImageViewController.init(image: image, cropFrame: CGRect(x: 0, y: 64, width: self.view.frame.size.width, height: self.view.frame.size.width), limitScaleRatio: Int(3.0))
        clipImageVC?.aspectType = Int32(aspectType);
        clipImageVC?.delegate = self

        DispatchQueue.main.async(){
            self.present(clipImageVC!, animated: true, completion: nil)
        }
        //获得照片
//        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
//        let newImage = resizeImage(image: image, size: CGSize(width: 95, height: 95))
//        NotificationCenter.default.addObserver(self, selector: #selector(refreshPicture), name: NSNotification.Name(rawValue: "refreshPicture"), object: nil)
//        
//        let fileData = zipImage(currentImage: newImage!, scaleSize: 1, percent: 0.5)
//        tsRequest.upload(fileData: fileData as NSData)
    }
    
    
    
    //MARK: mark - ClipImageDelegate
    func imageCropper(_ clipViewController: ClipImageViewController!, didFinished editedImage: UIImage!) {
        self.dismiss(animated: true, completion: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(refreshPicture), name: NSNotification.Name(rawValue: "refreshPicture"), object: nil)
        let fileData = zipImage(currentImage: editedImage!, scaleSize: 0.5, percent: 0.2)
        let index = funcForuUpload?.index((funcForuUpload?.endIndex)!, offsetBy: -10)
        let suffix = funcForuUpload?.substring(from: index!)
        tsRequest.upload(fileData: fileData as NSData,fileName:(suffix!+".jpg") as NSString)
    }
    
    func imageCropperDidCancel(_ clipViewController: ClipImageViewController!) {
        clipViewController.dismiss(animated: true, completion: nil)
    }
    
    
    func refreshPicture(notification:NSNotification)
    {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "refreshPicture"), object: nil)
        let result = notification.userInfo?["result"] as? NSDictionary
        let data = result?["data"] as? NSDictionary
        let value = data?["key"]
        let dic = ["key":value]
        let jsonStr = getJSONStringFromDictionary(dictionary: dic as NSDictionary)
        let jsFunction = NSString.init(format: "%@('%@')",funcForuUpload!,jsonStr) as String
        let _ = contextForuUpload?.evaluateScript(jsFunction)
    }
    
    //MARK:- TSDatePickerViewControllerDelegate
    func setDate(dateText: String?, jsFn: String?, modelContext: JSContext?)
    {
        let dic = ["key":dateText]
        let jsonStr = getJSONStringFromDictionary(dictionary: dic as NSDictionary)
        let jsFunction = NSString.init(format: "%@('%@')",jsFn!,jsonStr) as String
        let _ = modelContext?.evaluateScript(jsFunction)
    }
    
    //JOSN 字典转化为String
    func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData!
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
    }
    
    //判断当前是否处于登陆状态
    func checkLoginStatus() -> Bool{
        let requestDic = tsRequest.getUserInfo()
        let data = requestDic?["data"] as? NSDictionary
        if data == nil{
            return false
        }else{
            return true
        }
    }
    
    //MARK: - 调用系统分享机制
    func share(title:String?,url:String?)
    {
        DispatchQueue.main.async(){
            let activity = self.createActivityController(title: title, url: url)
            self.present(activity, animated: true, completion: nil)
        }
    }
    func createActivityController(title:String?,url:String?) -> UIActivityViewController {
        let shareImage = UIImage(named: "login_logo@2x.png")!
        let shareTitle = title != nil ? title:""
        let urlStr = url != nil ? url:""
        let shareURL = NSURL(string: urlStr!)!
        let activityViewController = UIActivityViewController(
            activityItems: [shareImage,shareTitle!,shareURL],
            applicationActivities: nil)
        activityViewController.excludedActivityTypes =  [
            UIActivityType.postToTwitter,
            UIActivityType.postToFacebook,
            UIActivityType.postToWeibo,
            UIActivityType.message,
            UIActivityType.mail,
            UIActivityType.print,
            UIActivityType.copyToPasteboard,
            UIActivityType.assignToContact,
            UIActivityType.saveToCameraRoll,
            UIActivityType.addToReadingList,
            UIActivityType.postToFlickr,
            UIActivityType.postToVimeo,
            UIActivityType.postToTencentWeibo,
            UIActivityType(rawValue: "com.apple.mobilenotes.SharingExtension"),
            UIActivityType(rawValue: "com.apple.reminders.RemindersEditorExtension")
        ]
        return activityViewController
    }
    
    //MARK:-获取首页顶部左右两边的image
    func downImage(urlString:String,barBtnItem:UIBarButtonItem)
    {
        let url : NSURL = NSURL(string: "\(urlString)")!
        let request = URLRequest(url: url as URL)
        let session = URLSession.shared
        let dataTask = session.dataTask(with: request, completionHandler: {
            (data, response, error) -> Void in
            if error != nil{
                print(error.debugDescription)
            }else{
                if data != nil{
                    let img = UIImage(data:data!)
                    // 这里需要改UI，需要回到主线程
                    DispatchQueue.main.async {
                        if img != nil{
                            barBtnItem.image = self.resizeImage(image: img!, size: CGSize(width: 20, height: 20))
                        }
                    }
                }
            }
        }) as URLSessionTask
        //使用resume方法启动任务
        dataTask.resume()
    }
    
    //设置图片大小尺寸
    func resizeImage(image: UIImage,size:CGSize) -> UIImage? {
        let newSize = CGSize(width: size.width, height: size.height)
        UIGraphicsBeginImageContext(newSize)
        image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
    
    func getFileSizeOfCache()-> Int {
        // 取出cache文件夹目录 缓存文件都在这个目录下
        let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
        //缓存目录路径
        // 取出文件夹下所有文件数组
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        //快速枚举出所有文件名 计算文件大小
        var size = 0
        for file in fileArr! {
            // 把文件名拼接到路径中
            let path = (cachePath! as NSString).appending("/\(file)")
            // 取出文件属性
            let floder = try! FileManager.default.attributesOfItem(atPath: path)
            // 用元组取出文件大小属性
            for (abc, bcd) in floder {
                // 累加文件大小
                if abc == FileAttributeKey.size {
                    size += (bcd as AnyObject).integerValue
                }
            }
        }
        let mm = size / 1024 / 1024
        return mm
    }
    
    func clearFileSizeOfCache() {
        // 取出cache文件夹目录 缓存文件都在这个目录下
        let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
        // 取出文件夹下所有文件数组
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        // 遍历删除
        for file in fileArr! {
            let path = (cachePath! as NSString).appending("/\(file)")
            if FileManager.default.fileExists(atPath: path) {
                do {
                    try FileManager.default.removeItem(atPath: path)
                    if getFileSizeOfCache() == 0{
                        DispatchQueue.main.async(){
                            let alertController = UIAlertController(title: "清理成功",message: nil, preferredStyle: .alert)
                            self.present(alertController, animated: true, completion: {
                                alertController.dismiss(animated: true, completion: nil)
                            })
                        }
                    }
                } catch {
                    
                }
            }
        }
    }
    

    //设置屏幕翻转
    func setDeviceOrientation(isPortrait:Bool){
        OperationQueue.main.addOperation(){
            let appDelegate = UIApplication.shared.delegate as! UIResponder
            let value: Int
            if isPortrait{
                appDelegate.allowRotation = false
                value = UIInterfaceOrientation.portrait.rawValue
                self.view.backgroundColor = UIColor.black
            }else{
                appDelegate.allowRotation = true
                value = UIInterfaceOrientation.landscapeLeft.rawValue
                self.view.backgroundColor = UIColor.white
            }
            self.view.setNeedsDisplay()
            UIDevice.current.setValue(value, forKey: "orientation")
        }
    }
    
    override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
//        let statusBarHeight = UIApplication.shared.statusBarFrame.height
//        let navigationBarHeight:CGFloat = 44 + statusBarHeight
//        if toInterfaceOrientation.isLandscape{
//            webView.snp.makeConstraints { (make) in
//                make.top.equalTo(30)
//                make.bottom.equalTo(view)
//                make.left.equalTo(view)
//                make.right.equalTo(view)
//            }
//        }else{
//            webView.snp.makeConstraints { (make) in
//                make.top.equalTo(navigationBarHeight)
//                make.bottom.equalTo(view)
//                make.left.equalTo(view)
//                make.right.equalTo(view)
//            }
//        }
    }
    
    
    //MARK:-压缩图片大小
    func zipImage(currentImage: UIImage,scaleSize:CGFloat,percent: CGFloat) -> NSData{
        //压缩图片尺寸
        UIGraphicsBeginImageContext(CGSize(width: currentImage.size.width*scaleSize, height: currentImage.size.height*scaleSize))
        currentImage.draw(in: CGRect(x: 0, y: 0, width: currentImage.size.width*scaleSize, height:currentImage.size.height*scaleSize))
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        //高保真压缩图片质量
        let imageData: NSData = UIImageJPEGRepresentation(newImage, percent)! as NSData
        return imageData
    }
}
